﻿using System;
using CtefCrmImport.Common.Enums;
using CtefCrmImport.Common.Extensions;
using CtefCrmImport.Common.Interfaces;
using CtefCrmImport.Common.Models;

namespace CtefCrmImport.Common.Builders
{
    public class DonationBuilder2 : IEntityBuilder<Donation>
    {
        public Donation BuildEntity(string input)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                throw new ArgumentException("Invalid line input.", "input");
            }

            // Use tab delimited format (file should be exported from Excel as unicode text file)
            var fields = input.Split('\t');
            var address = new Address
            {
                AddressLine1 = fields[11].TrimOrEmpty(),
                AddressLine2 = fields[12].TrimOrEmpty(),
                City = fields[13].TrimOrEmpty(),
                State = fields[14].TrimOrEmpty(),
                Zip = fields[15].TrimOrEmpty()
            };

            var donor = new Donor
            {
                LastName = fields[0].TrimOrDefault("CTEF"),
                FirstName = fields[1].TrimOrDefault("Friend"),
                MiddleName = fields[2].TrimOrEmpty(),
                ChineseName = fields[3].TrimOrEmpty(),
                PrimaryEmail = fields[16].TrimOrEmpty(),
                EmailForStudents = fields[17].TrimOrEmpty(),
                Address = address
            };

            var donation = new Donation
            {
                LineInput = input,
                From = donor,
                GiftAmount = decimal.Parse(fields[7]),
                RecognitionName = fields[10].TrimOrEmpty(),
                OtherInfo = fields[18].TrimOrEmpty()
            };

            DateTime date;
            donation.Date = DateTime.TryParse(fields[4], out date) ? date : DateTime.Now;

            decimal amount;
            if (decimal.TryParse(fields[8], out amount))
            {
                donation.CompanyMatch = amount;
            }

            donation.FundType = fields[5].ToDonationType();
            if (donation.FundType == DonationType.Unspecified)
            {
                // type is required and use general fund as the default
                donation.FundType = DonationType.GeneralFund;
                donation.Purpose = fields[5].TrimOrEmpty();
            }

            donation.PaymentInstrument = fields[6].ToPaymentType();
            if (donation.PaymentInstrument == PaymentType.Other)
            {
                donation.OtherInfo += Environment.NewLine + string.Format("Payment type: {0}", fields[6]);
            }

            return donation;
        }
    }
}
